<template>
    <div class="orders">
     <HeaderNav></HeaderNav>
     <div class="content">
       <div class="search-bar">
        <input type="text" placeholder="搜索回复内容"  v-model="searchQuery">
        <button class="add-button" @click="openAddModal">添加订单</button>
      </div>
      <div class="table-container">
        <table class="data-table">
          <thead>
            <tr>
              <th class="name-column">商品编号</th>
              <th class="user-column">用户编号</th>
              <th class="quantity-column">用户名称</th>
              <th class="quantity-column">发帖内容</th>
              <th class="image-column">发帖时间</th>
              <th class="action-column">操作</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="item in filteredReviews" :key="item.userid">
              <td class="name-column">{{ item.gid }}</td>
              <td class="user-column">{{ item.userId }}</td>
              <td class="quantity-column">{{ item.username }}</td>
              <td class="quantity-column">{{ item.contents }}</td>
              <td class="image-column">{{ item.formatted_rvtime }}</td>
              <td class="action-column">
                <button class="delete-button" @click="openEditModal(item)">编辑</button>
                <button class="del-button" @click="confirmDelete(item.rvid)">删除</button>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
     </div>

      <!-- 编辑模态框 -->
    <div v-if="showEditModal" class="modal-overlay">
      <div class="modal-content">
        <h2>编辑商品信息</h2>
        <form @submit.prevent="savereview">
          <div class="form-group">
            <label>回复编号</label>
            <input v-model="editingreview.rvid" type="number" required>
          </div>
          <div class="form-group">
            <label>商品编号</label>
            <input v-model="editingreview.gid" type="number" required>
          </div>
          <div class="form-group">
            <label>用户编号</label>
            <input v-model="editingreview.userId" type="number">
          </div>
           <div class="form-group">
            <label>内容</label>
              <input v-model="editingreview.contents" type="text">
          </div>
          <div class="form-actions">
            <button type="button" @click="closeEditModal" class="cancel-button">取消</button>
            <button type="submit" class="save-button" >保存</button>
          </div>
        </form>
      </div>
    </div>

     <!-- 添加评论模态框 -->
<div v-if="showAddModal" class="modal-overlay">
  <div class="modal-content">
    <h2>添加新评论</h2>
    <form @submit.prevent="addreview">
      <div class="form-group">
        <label>商品编号</label>
        <input v-model="newreview.gid" type="number" required>
      </div>
      <div class="form-group">
        <label>用户编号</label>
         <input v-model="newreview.userid" type="number">
      </div>
      <div class="form-group">
        <label>内容</label>
        <input v-model="newreview.contents" type="text">
      </div>
      <div class="form-actions">
        <button type="button" @click="closeAddModal" class="cancel-button">取消</button>
        <button type="submit" class="save-button">保存</button>
      </div>
    </form>
  </div>
  </div>
    </div>
  </template>
  
  <script setup>
import HeaderNav from '@/views/admin/HeaderNav.vue';
import axios from '../../api/axios';
import { useRoute } from 'vue-router'
import { ref,computed } from 'vue'
const searchQuery = ref('')
const showEditModal = ref(false)
const editingreview = ref({})

const showAddModal = ref(false);
const selectedFile = ref(null);
const newreview = ref({
  gid: '',
  userid: '',
  contents: '',
});

// 打开添加模态框
const openAddModal = () => {
  newreview.value = {
    gid: '',
    userid: '',
    contents: '',
  };
  selectedFile.value = null;
  showAddModal.value = true;
};

// 关闭添加模态框
const closeAddModal = () => {
  showAddModal.value = false;
  selectedFile.value = null;
};

const addreview = async () => {
  const now = new Date();
    const year = now.getFullYear();
    const month = String(now.getMonth() + 1).padStart(2, '0');
    const day = String(now.getDate()).padStart(2, '0');
    const hours = String(now.getHours()).padStart(2, '0');
    const minutes = String(now.getMinutes()).padStart(2, '0');
    const seconds = String(now.getSeconds()).padStart(2, '0');
    
    const rvtime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
  const payload = {
    gid: Number(newreview.value.gid),
    userid: Number(newreview.value.userid),
    contents: newreview.value.contents,
    rvtime: rvtime
    };

    const response = await axios.post('/api/reviews/addreviews', payload);
    if (response.data.code === 200) {
      alert('添加成功');
      fetchreviews();
      closeAddModal();
    } else {
      alert('添加失败: ' + (response.data.msg || '未知错误'));
  } 
}

const userReviews = ref([])
const fetchreviews = () => {
axios.post('/api/reviews/userReviews',).then((res) => {
  console.log(res.data)
  if (res.data.code === 200) {
    userReviews.value = res.data.reviews;
    // console.log(reviewsBygid.value)
  }
}).catch((err) => {
  console.error("请求失败", err);
})
}
fetchreviews();

// 搜索过滤
const filteredReviews = computed(() => {
  return userReviews.value.filter(reviews => 
    reviews.contents.toLowerCase().includes(searchQuery.value.toLowerCase()) 
  )
})
// 打开编辑模态框
const openEditModal = (reviews) => {
  editingreview.value = { ...reviews };
  showEditModal.value = true;
};

// 关闭编辑模态框
const closeEditModal = () => {
  showEditModal.value = false;
};

const savereview = () => {
    const payload = {
        rvid: Number(editingreview.value.rvid),
        gid: Number(editingreview.value.gid),
        userid: Number(editingreview.value.userId),
        contents: editingreview.value.contents
    };

     axios.post('/api/reviews/updatereviews', payload)
        .then(res => {
            if (res.data.code === 200) {
                alert('订单信息更新成功');
                fetchreviews();
                closeEditModal();
            } else {
                alert('更新失败: ' + (res.data.msg || '未知错误'));
            }
        })
        .catch(err => {
            console.error("请求失败:", err);
            alert('更新失败，请检查控制台');
        });
  }

  // 确认删除
const confirmDelete = (rvid) => {
  if(confirm('确定要删除这个订单吗？')) {
    deletereview(rvid);
  }
};

// 删除商品
const deletereview = async (rvid) => {
  try {
    const response = await axios.post('/api/reviews/delreviews', { rvid });
    if (response.data.code === 200) {
      alert('删除成功');
      fetchreviews(); // 刷新列表
    } else {
      alert('删除失败: ' + (response.data.msg || '未知错误'));
    }
  } catch (err) {
    console.error("删除失败:", err);
    alert('删除失败，请检查控制台');
  }
};
  </script>
  
  <style lang="scss" scoped>
  .orders {
  display: flex;
  font-family: 'Arial', sans-serif;
  }
  .content {
  max-width: 1200px;
  margin: 20px auto;
  padding: 20px;
  background-color: #f9f9f9;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}
.search-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

input {
  width: 30%;
  padding: 10px;
  border: 1px solid #ccc;
  border-radius: 4px;
  margin-right: 10px;
}

.table-container {
  overflow-x: auto;
}

.data-table {
  width: 100%;
  border-collapse: collapse;
  min-width: 1160px; /* 确保表格在不同屏幕尺寸下都能良好显示 */
}

.data-table th,
.data-table td {
  text-align: left;
  padding: 10px;
  border-bottom: 1px solid #ddd;
}

.data-table th {
  background-color: #f2f2f2;
}

.data-table tr:hover {
  background-color: #f5f5f5;
}

.name-column, .user-column{
  width: 15%;
}

.price-column,
.quantity-column,
.action-column {
  width: 15%;
}

.image-column {
  width: 20%;
}

.edit-button,
.delete-button {
  padding: 5px 10px;
  margin-right: 5px;
  border: none;
  border-radius: 4px;
  background-color: #007BFF;
  color: #fff;
  cursor: pointer;
}

.edit-button:hover,
.delete-button:hover {
  background-color: #0056b3;
}

// 删除按钮
.del-button {
  padding: 5px 10px;
  border: none;
  border-radius: 4px;
  background-color: #dc3545;
  color: #fff;
  cursor: pointer;
}

.del-button:hover {
  background-color: #c82333;
}

/* 模态框样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal-content {
  background-color: white;
  padding: 20px;
  border-radius: 8px;
  width: 500px;
  max-width: 90%;
}

.modal-content h2 {
  margin-top: 0;
  margin-bottom: 20px;
}

.form-group {
  margin-bottom: 15px;
}

.form-group label {
  display: block;
  margin-bottom: 5px;
  font-weight: bold;
}

.form-group input,
.form-group select {
  width: 100%;
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
  box-sizing: border-box;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

.cancel-button {
  padding: 8px 16px;
  margin-right: 10px;
  background-color: #f0f0f0;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.save-button {
  padding: 8px 16px;
  background-color: #007BFF;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.save-button:hover {
  background-color: #0056b3;
}

.form-group input[type="file"] {
  padding: 5px;
  border: 1px dashed #ccc;
  border-radius: 4px;
  background-color: #f9f9f9;
}

.add-button {
  padding: 10px 15px;
  background-color: #28a745;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  margin-left: 10px;
}

.add-button:hover {
  background-color: #218838;
}
  </style>